<template>
  <el-dialog
    :model-value="modelValue" 
    :title="title + '权限'"
    :before-close="onClose"
    lock-scroll
  >
    <el-tree
      style="max-height:80vh; overflow-y: scroll;"
      ref="treeRef"
      empty-text="暂无数据"
      :data="roleAuths"
      :props="defaultProps"
      :show-checkbox="type === 'edit' ? true : false"
      :node-key="treeNodeKey"
      accordion
      check-strictly
    />
    <template #footer v-if="type === 'edit'">
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {getRoleAuths} from '@/service/permission'
import {flatArrayObject} from '@/function/array'

// eslint-disable-next-line
const emits = defineEmits(['update:modelValue'])
// eslint-disable-next-line
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  type: {
    type: String,
    required: true
  },
  roleId: {
    type: Number,
    required: true
  },
  treeNodeKey: {
    type: String,
    default: 'id'
  }
})

const treeRef = ref(null)
const roleAuths = ref([])
const defaultProps = {
  children: 'menu',
  label: 'menuName'
}

watch(() => props.roleId, () => {
  getRolelist()
})

/* methods */
async function getRolelist() {
  const {flag, data} = await getRoleAuths(props.roleId)
  if (flag) {
    roleAuths.value = data
    if (props.type === 'edit') {
      treeRef.value.setCheckedKeys(flatArrayObject(data).map(i => i.id))
    }
  }
}
function onClose() {
  emits('update:modelValue', false)
}
function onConfirm() {
  ElMessage.success('成功，请到控制台查看选择的key')
  console.log(treeRef.value.getCheckedKeys())
  onClose()
}
</script>
